package org.vectrics.mail;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;

import org.apache.log4j.Logger;
import org.vectrics.user.Person;

public class MailRecipientManager {
	private transient final Logger log = Logger.getLogger(this.getClass());
	
	public MailRecipientManager() {
		super();
	}

	public Set findRecipientClasses(Set persons) {
		Set classes = new HashSet();
		Iterator iter = persons.iterator();
		while (iter.hasNext()) {
			Person person = (Person)iter.next();
			if (person.getContactInfo() != null) {
				boolean html = false;
				if ((person.getContactInfo().getHtmlEmail() != null) && (person.getContactInfo().getHtmlEmail().booleanValue())) {
					html = true;
				}
				MailRecipientClass recipClass = this.findCreateClass(classes, 
								person.getLocale().getLocale(), html);
				recipClass.getPersons().add(person);
				classes.add(recipClass);
			}
		}
		
		return(classes);
	}
	
	private MailRecipientClass findCreateClass(Set classes, Locale locale, boolean html) {
		MailRecipientClass recipientClass = null;
		Iterator iter = classes.iterator();
		while ((recipientClass == null) && (iter.hasNext())) {
			MailRecipientClass curClass = (MailRecipientClass)iter.next();
			if ((curClass.getLocale().equals(locale)) && (curClass.getHtml() == html)) {
				recipientClass = curClass;
			}
		}
		if (recipientClass == null) {
			log.debug("Could not find recipient class, creating new one");
			recipientClass = new MailRecipientClass();
			recipientClass.setLocale(locale);
			recipientClass.setHtml(html);
		}
		return(recipientClass);
	}
}
